<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户维护</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片布局 -->
		<el-card class="box-card" style="opacity: 0.8;">
			<!-- 搜索框与添加用户按钮 -->
			<el-row :gutter="20">
				<el-col :span="6">
					<!-- 模糊搜索框 -->
					<el-input placeholder="请输入查询条件" class="input-with-select" clearable @clear="select"
						v-model="queryinfo.username">
						<el-button slot="append" icon="el-icon-search" @click="select">查询</el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addDialog=true">添加管理员</el-button>
				</el-col>
			</el-row>
			<el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
				element-loading-background="rgba(0, 0, 0, 0.8)" :data="users" border style="width: 100%;" class="table">
				<el-table-column type="index" label="" width="100">
				</el-table-column>
				<el-table-column prop="username" label="用户名" width="100">
				</el-table-column>
				<el-table-column label="角色" width="150">
					<template slot-scope="scope">
						<div v-for="val in scope.row.roles" :key="val.roleid">{{val.rolename}}</div>
					</template>
				</el-table-column>
				<el-table-column prop="sex" label="性别" width="100">
				</el-table-column>
				<el-table-column prop="age" label="年龄" width="100">
				</el-table-column>
				<el-table-column prop="email" label="邮箱" width="150">
				</el-table-column>
				<el-table-column label="头像" width="200">
					<!-- 作用域插槽 -->
					<template slot-scope="scope">
						<!-- {{scope.row.tx}} -->
						<el-image style="width: 80px; height: 60px" :src="imgurl+scope.row.tx" :fit="fit"></el-image>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<!-- 作用域插槽 -->
					<template slot-scope="scope">
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.userid)">
						</el-button>
						<el-tooltip class="item" enterable:false effect="dark" content="分配角色" placement="top">
							<el-button type="warning" @click="selectroles(scope.row.userid)" icon="el-icon-star-off"
								size="mini"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>

			</el-table>
			<!-- size-change:每页显示的条数改变时触发的函数
			      current-change：当前页码改变时触发的函数
		    -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryinfo.pagenum" :page-sizes="[1, 2, 4, 5]" :page-size="queryinfo.pagesize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>

		<!-- 分配用户角色的对话框 -->
		<!-- visible.sync:当前对话框是否显示
	     before-close:关闭前的提示-->
		<el-dialog title="分配用户角色" :visible.sync="roleDialogVisible" width="20%" :before-close="rolereset">
			<!--分配用户角色的表单 -->
			用户名：<el-input v-model="roleUser.username" style="width: 50%;"></el-input><br />
			角色：<br>
			<el-checkbox v-for="val in roles" :label="val.roleid" :key="val.roleid" v-model="rs">
				{{val.rolename}}
			</el-checkbox>
			<br />
			<!-- 取消和确定按钮 -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="rolereset">取 消</el-button>
				<el-button type="primary" @click="roleform">确定</el-button>
			</span>
		</el-dialog>

		<!-- 添加管理员 -->
		<center>
			<el-dialog title="添加管理员" :visible.sync="addDialog" width="40%" :before-close="addreset">
				<el-form class="addManager_form" ref="registerref" :model="registerform" :rules="registerrules"
					label-width="30%">
					<el-form-item label="管理员账号" prop="username">
						<el-input v-model="registerform.username" placeholder="请输入管理员账号名称" style="width: 80%;">
						</el-input>
					</el-form-item>
					<el-form-item label="密码" prop="password">
						<el-input type="password" v-model="registerform.password" placeholder="请输入密码" show-password
							prefix-icon="el-icon-lock" style="width: 80%;"></el-input>
					</el-form-item>
					<el-form-item label="确认密码" prop="checkPass">
						<el-input type="password" v-model="registerform.checkPass" autocomplete="off" show-password
							style="width: 80%;"></el-input>
					</el-form-item>
					<el-form-item label="性别">
						<el-radio-group v-model="registerform.sex">
							<el-radio label="男"></el-radio>
							<el-radio label="女"></el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="年龄" prop="age">
						<el-input v-model="registerform.age" placeholder="请输入年龄" style="width: 80%;"></el-input>
					</el-form-item>
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="registerform.email" placeholder="请输入邮箱" style="width: 80%;"></el-input>
					</el-form-item>
					<el-form-item label="头像">
						<!-- 图片上传 -->
						<!-- action:默认上传的路径 
	   	list-type：上传组件的样式
	   	on-preview：图片放大函数
	   	on-remove：图片移除的函数
	   	on-success：上传成功后的函数-->
						<el-upload action="http://localhost:8888/crowdfunding_system_war_exploded/upload"
							list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
							:on-success="addSuccess" :file-list="filelist">
							<i class="el-icon-plus"></i>
						</el-upload>
						<!-- 图片放大后的对话框 -->
						<el-dialog :visible.sync="dialogVisible">
							<img width="100%" :src="dialogImageUrl" alt="">
						</el-dialog>
					</el-form-item>
					<!-- 注册确定 -->
					<el-button type="primary" @click="submit">确定添加</el-button>
					<!-- 重置 -->
					<el-button type="info" @click="reset">重置</el-button>
				</el-form>
			</el-dialog>
		</center>
	</div>
</template>

<script>
	// 引入qs依赖
	import qs from 'qs';
	export default {
		data() {
			// 自定义邮箱验证的规则
			var checkEmail = ((rule, value, callback) => {
				if (!value) { //value为空
					return callback(new Error('邮箱不能为空'))
				}
				//判断是否符合邮箱的正则表达式
				var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
				if (!reg.test(value)) {
					return callback(new Error('邮箱格式不合法'))
				}
				return callback();
			});
			var validatePass = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'));
				} else if (value !== this.registerform.password) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				// 查询条件信息
				queryinfo: {
					username: '', //用户名模糊查询
					pagenum: 1, //访问的页码
					pagesize: 4 //默认每页展示的条数
				},
				//保存查询到的用户信息
				users: [],
				// 总条数
				total: 0,
				imgurl: 'http://localhost:8888/crowdfunding_system_war_exploded/showimg?filename=',
				// 分配角色的对象
				roleUser: {
					userid: '',
					roleid: ''
				},
				// 角色集合
				roles: [],
				// 角色id数组
				rids: [],

				rs: [],
				// 分配角色对话框关闭
				roleDialogVisible: false,
				// 添加管理员
				addDialog: false,
				// 添加用户对象
				registerform: {
					address: '',
					username: '',
					password: '',
					checkPass: '',
					sex: '',
					age: '',
					email: '',
					aid: '',
					tx: '',
					token: '',

				},

				registerrules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 5,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 6,
							message: '长度在 6 个字符',
							trigger: 'blur'
						}
					],
					checkPass: [{
						validator: validatePass,
						trigger: 'blur'
					}],
					email: [{
						validator: checkEmail,
						trigger: 'blur'
					}]
				},
				dialogImageUrl: '',
				dialogVisible: false,
				filelist: [],

			}
		},

		methods: {
			// 查询所有数据
			async selectUsers() {

				var res = await this.$http.post("selectUser", qs.stringify(this.queryinfo));
				// console.log(res)
				if (res.data.code == 400) {
					this.$message.error(res.data.message);
				} else {
					console.log(res.data);
					this.users = res.data.data.list;
					this.total = res.data.data.total;

				}
			},
			// 根据用户名模糊查询
			select() {
				this.queryinfo.pagenum = 1;
				this.selectUsers()
			},
			// 每页条数改变的函数
			handleSizeChange(newpagesize) {
				this.queryinfo.pagesize = newpagesize;
				this.queryinfo.pagenum = 1;
				this.selectUsers()
			},
			// 改变查询页数的函数
			handleCurrentChange(newpagenum) {
				this.queryinfo.pagenum = newpagenum;
				this.selectUsers()
			},
			// 删除确定
			delUser(id) {
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}, ).then(async () => {
					var res = await this.$http.get('delUser?id=' + id);
					if (res.data.code == 200) {
						this.$message.success(res.data.message);
						this.selectUsers();
					} else {
						this.$message.error(res.data.message);
					}
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},

			// 分配角色
			async selectroles(id) {
				var res = await this.$http.get('selectuserrole?id=' + id);
				if (res.data.code == 200) {
					// 展开分配角色的对话框
					this.roleDialogVisible = true;
					// 获取当前用户信息
					console.log(res.data.data)
					this.roleUser = res.data.data.user;
					this.roles = res.data.data.role;
					if (this.roleUser.roles.length == 0) {
						// this.rs.push(this.roleUser);
					} else {
						// 动态获取当前对象所属的角色的id
						for (var i = 0; i < this.roleUser.roles.length; i++) {
							this.rs.push(this.roleUser.roles[i].roleid);
						}
					}


				} else {
					this.$message.error('查询失败');
				}
			},
			// 取消分配角色
			rolereset() {
				this.roleDialogVisible = false;
				this.roleUser = {};
				this.roles = [];
				this.rs = []
			},
			// 分配角色的确定按钮
			async roleform() {
				// 关闭对话框
				
				this.roleDialogVisible = false;

				var res = await this.$http.get('insertRole?userid=' + this.roleUser.userid + '&&roleid=' + this.rs);
			console.log(this.rs)
				if (res.data.code == 200) {
					this.$message.success(res.data.message);
					this.selectUsers()
				} else {
					this.$message.error(res.data.message);
				}
				this.roleUser = {};
				this.roles = [];
				this.rs = [];
			},
			// 添加管理员
			submit() {
				this.$refs.registerref.validate(async (bo) => {
					if (bo) {
						var res = await this.$http.post('addManager', qs.stringify(this.registerform));
						// 处理返回值信息，并给出不同的信息提示
						if (res.data.code == 200) { // 添加成功
							this.$message.success(res.data.message);
							this.addDialog = false
							this.selectUsers()
						} else {
							this.$message.error(res.data.message);
						}
					} else {
						this.$message.error('格式不合法');
					}
				})
			},
			// 关闭添加对话框
			addreset() {
				this.$refs.registerref.resetFields();
				this.filelist = [];
				this.addDialog = false
			},
			// 重置添加信息
			reset() {
				this.$refs.registerref.resetFields();
				this.filelist = [];
				this.selectUsers()
			},
			// 图片移除
			handleRemove(file, fileList) {
				// console.log(file, fileList);
				this.registerform.tx = '';
			},
			// 图片放大
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			// 图片上传成功后的函数
			addSuccess(res) {
				// console.log(res)
				if (res.code == 200) {
					this.registerform.tx = res.message;
				}
			},

		},
		mounted() {
			this.selectUsers()
		}
	}
</script>

<style>
	.addManager_form {}
</style>
